#include "level.h"

Level::Level(const sf::Vector2<float>& position, const sf::Vector2<float>& size)
{
	mPosition = position;
	mSize.x = (float)((int)size.x);
	mSize.y = (float)((int)size.y);
	mDrawBorderFlag = false;

	LevelComponents::Room r(mPosition, mSize);
	r.Create(mMapObjects);
}

void Level::draw(sf::RenderWindow& context)
{
	for(int x = 0; x < mSize.x; x++)
	{
		for(int y = 0; y < mSize.y; y++)
		{
			mMapObjects[x][y].draw(context);
		}
	}
	if(mDrawBorderFlag)
		context.Draw(sf::Shape::Rectangle(mPosition.x, mPosition.y, mSize.x*GameSettings::TileSize, mSize.y*GameSettings::TileSize, sf::Color(0,0,0,0), 1.0f, sf::Color(80,80,80)));
}

void Level::setDrawBorder(bool draw)
{
	mDrawBorderFlag = draw;
}

namespace LevelComponents
{
	Room::Room(const sf::Vector2<float> position, const sf::Vector2<float>& size)
	{
		mPosition = position;
		mSize = size;
		mNumDoors = 3;
	}

	void Room::Create(std::vector<std::vector<BaseObject>>& mapObjects)
	{
		// First, create walls and a floor
		for(int x = 0; x < mSize.x; x++)
		{
			std::vector<BaseObject> newLine;
			mapObjects.push_back(newLine);

			for(int y = 0; y < mSize.y; y++)
			{
				// If we're at the edge of the "map"
				if(x == 0 || x == (mSize.x-1) || y == 0 || y == (mSize.y-1))
				{
					Wall w;
					w.setPosition(mPosition + sf::Vector2<float>((float)x*GameSettings::TileSize, (float)y*GameSettings::TileSize));

					mapObjects[x].push_back(w);
				}
				else	// Else, stick some floor there
				{
					Dirt d;
					d.setPosition(mPosition + sf::Vector2<float>(x*GameSettings::TileSize, y*GameSettings::TileSize));

					mapObjects[x].push_back(d);
				}
			}
		}
		for(int i = 0; i < mNumDoors; i++)	// Place doors
		{
			// Which side to put it on
			int side = sf::Randomizer::Random(0, 3);
			int displacement = sf::Randomizer::Random(0, (int)mSize.y-1);	// How far along the wall this door is
			int tileDisp = displacement*GameSettings::TileSize;

			Door d;

			switch(side)
			{
			case(0):	// Left
				d.setPosition(mPosition + sf::Vector2<float>(0, tileDisp));
				mapObjects[0][displacement] = d;
				break;
			case(1):	// Right
				d.setPosition(mPosition + sf::Vector2<float>((mSize.x-1)*GameSettings::TileSize, tileDisp));
				mapObjects[mSize.x-1][displacement] = d;
				break;
			case(2):	// Top
				d.setPosition(mPosition + sf::Vector2<float>(tileDisp, 0));
				mapObjects[displacement][0] = d;
				break;
			case(3):	// Bottom
				d.setPosition(mPosition + sf::Vector2<float>(tileDisp, (mSize.y-1)*GameSettings::TileSize-1));
				mapObjects[displacement][mSize.y-1] = d;
				break;
			}
		}
	}
};